<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">{{ title }}</h3>

      <!-- 登录方式切换 -->
      <el-tabs v-model="activeTab" stretch>
        <el-tab-pane label="账号密码登录" name="password"></el-tab-pane>
        <el-tab-pane label="私钥文件登录" name="privateKey"></el-tab-pane>
      </el-tabs>
      <!--上述组件 “el-tabs” 使用点击方式进行切换-->

      <!--下述语句 表示默认方式为使用账号密码进行登录-->
      <template v-if="activeTab === 'password'"> 
        <!-- 用户名输入框 -->
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            auto-complete="off"
            placeholder="账号"
          ><!--其中auto-->
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
          </el-input>
        </el-form-item>

        <!-- 密码模式 -->

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
          </el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item prop="code" v-if="captchaEnabled">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </el-form-item>

        <!-- 记住密码 -->
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      </template>

      <!-- 私钥文件模式 -->
      <template v-else>
        <el-form-item prop="privateKey">
          <el-upload
            class="upload-privatekey"
            action=""
            :show-file-list="false"
            :before-upload="handlePrivateKeyUpload"
          >
            <el-button size="small" type="primary">选择私钥文件</el-button>
            <span v-if="privateKeyFileName" style="margin-left: 10px;">{{ privateKeyFileName }}</span>
          </el-upload>
        </el-form-item>
        <el-form-item prop="did" v-if="did!==''">
          <el-input
            v-model="did"
            type="text"
            auto-complete="off"
            placeholder="DID"
            disabled
          >
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
          </el-input>
        </el-form-item>
      </template>

      <!-- 登录按钮 -->
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>

    <!-- 底部 -->
    <div class="el-login-footer">
      <span>Copyright © 2025 shanxi-grid All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import {getCodeImg, getPKLoginUUID} from "@/api/login"
import Cookies from "js-cookie"
import {encrypt, decrypt} from "@/utils/jsencrypt"
import nacl from "tweetnacl";
import naclUtil from "tweetnacl-util";
import bs58 from "bs58";

export default {
  name: "Login",
  data() {
    return {
      title: process.env.VUE_APP_TITLE,
      activeTab: "password", // 登录方式切换
      codeUrl: "",
      loginForm: {
        username: "admin",
        password: "admin123",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      keyPair: null,
      privateKey: "",
      privateKeyFileName: "",
      pkLoginUUID: "",
      did: "",
      loginRules: {
        username: [{required: true, trigger: "blur", message: "请输入您的账号"}],
        password: [{required: true, trigger: "blur", message: "请输入您的密码"}],
        code: [{required: true, trigger: "change", message: "请输入验证码"}]
      },
      loading: false,
      captchaEnabled: true,
      register: false,
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.getCode()
    this.getCookie()
    this.getPkLoginUUID()
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img
          this.loginForm.uuid = res.uuid
        }
      })
    },
    getCookie() {
      const username = Cookies.get("username")
      const password = Cookies.get("password")
      const rememberMe = Cookies.get("rememberMe")
      this.loginForm = {
        ...this.loginForm,
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      }
    },
    getPkLoginUUID() {
      getPKLoginUUID().then(res => {
        this.pkLoginUUID = res.pkLoginUUID
      })
    },
    // 处理私钥文件上传（本地读取）
    handlePrivateKeyUpload(file) {
      this.privateKeyFileName = file.name
      const reader = new FileReader() // 使用读取而非真正上传文件
      reader.readAsText(file)
      reader.onload = e => {
        this.privateKey = e.target.result // 把私钥内容存到 loginForm
        this.privateKeyToPk(this.privateKey)
      }
      return false // 阻止默认上传
    },
    privateKeyToPk(privateKey) {
      // 去掉 PEM 头尾
      const pem = privateKey
        .replace("-----BEGIN PRIVATE KEY-----", "")
        .replace("-----END PRIVATE KEY-----", "")
        .replace(/\s+/g, "");

      // Base64 解码
      const secretKey = naclUtil.decodeBase64(pem);

      // tweetnacl 要求私钥长度为 64 字节，如果你的 PEM 是 32 字节种子，需要自己生成 keypair
      let keyPair;
      if (secretKey.length === 32) {
        keyPair = nacl.sign.keyPair.fromSeed(secretKey);
      } else if (secretKey.length === 64) {
        keyPair = nacl.sign.keyPair.fromSecretKey(secretKey);
      } else {
        console.error("私钥长度不正确");
        return;
      }
      // this.publicKey = naclUtil.encodeBase64(keyPair.publicKey);
      this.keyPair = keyPair;
      this.publicKey = bs58.encode(keyPair.publicKey);
      console.log(this.publicKey)
      this.pkToDID()
    },
    pkToDID() {
      if (this.publicKey != null && this.publicKey !== "") {
        let pk_bytes = bs58.decode(this.publicKey)
        let last10 = pk_bytes.slice(-10);
        let did = "did:grid:" + bs58.encode(last10).toLowerCase();
        this.did = did
        console.log("did:", this.did)
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
           this.loading = true
      this.$store.dispatch('Login', this.loginForm).then(res => {
        // ✅ 关键部分：保存角色标识
        // 后端返回的登录结果中应该包含用户角色，如 res.roleKey = "DMS"
        localStorage.setItem('roleKey', res.roleKey)

        // 跳转到首页或指定路由
        this.$router.push({ path: '/' })
      }).catch(() => {
        this.loading = false
      })
        }
        // this.loading = true
        
        if (this.activeTab === "password") {
          // ======= 账号密码登录 =======
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, {expires: 30})
            Cookies.set("password", encrypt(this.loginForm.password), {expires: 30})
            Cookies.set("rememberMe", this.loginForm.rememberMe, {expires: 30})
          } else {
            Cookies.remove("username")
            Cookies.remove("password")
            Cookies.remove("rememberMe")
          }

          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.$router.push({path: this.redirect || "/"}).catch(() => {
              })
            })
            .catch(() => {
              this.loading = false
              if (this.captchaEnabled) {
                this.getCode()
              }
            })
        } else {
          // ======= 私钥文件登录 =======
          if (!this.privateKey) {
            this.$message.error("请先选择私钥文件")
            this.loading = false
            return
          }
          // 3. 使用私钥签名
          const messageUint8 = naclUtil.decodeUTF8(this.pkLoginUUID);
          const signature = nacl.sign.detached(messageUint8, this.keyPair.secretKey);
          this.$store
            .dispatch("LoginWithPK", {
              did: this.did,
              pkLoginUUID: this.pkLoginUUID,
              sign: bs58.encode(signature)
            })
            .then(res => {
              console.log("res:", res)
              this.$router.push({path: this.redirect || "/"}).catch(() => {
              })
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  z-index: 1;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}

.upload-privatekey {
  display: flex;
  align-items: center;
}
</style>
